<template>
  <page-header-wrapper :title="false">
    <div class="cardArea">
      <!-- 标题 -->
      <div class="cardArea_title">
        <div class="cardArea_title_label"></div>
        <div class="cardArea_title_content">表单配置</div>
      </div>
      <div class="cardArea_step">
        <template>
          <a-steps class="stepBox" :current="stepIndex" @change="stepChange">
            <a-step title="第一步" description="选择流程" />
            <a-step title="第二步" description="表单基本信息" />
            <a-step title="第三步" description="选择数据表" />
            <a-step title="第四步" description="界面布局" @click="stepChange(stepIndex)" />
          </a-steps>
        </template>
      </div>
    </div>

    <a-card style="margin-top: 1em" :loading="pageLoad">
      <!-- 步骤一 -->
      <div v-if="pageIndex == 0" ref="imgTooles">
        <div class="titlebox">选择流程</div>
        <div class="bodyBox">
          <a-form-item label="请选择流程" required prop="key_" :label-col="{ span: 6 }">
            <a-select
              ref="proSelect"
              v-if="!formInfo.formid"
              v-model="formInfo.step2.key_"
              style="width: 50%"
              placeholder="请选择流程"
              @change="processChange"
            >
              <a-select-option v-for="item in processList" :key="item.model_key" :value="item.model_key">
                {{ item.name }}
              </a-select-option>
            </a-select>
            <span v-else v-text="formInfo.step2.name_"></span>
            <a style="margin-left: 10px" :disabled="imageLoading" @click="getFlowImage">预览流程图</a>
          </a-form-item>
          <a-form-item v-show="!!url" label="流程图预览" :label-col="{ span: 6 }">
            <div style="display: flex; align-items: center; justify-content: center">
              <img
                style="width: auto; height: auto; max-width: 100%; max-height: 100%"
                :src="url"
                :data-original="url"
                @click="initImageTools"
              />
            </div>
          </a-form-item>
        </div>
      </div>

      <!-- 步骤二 -->
      <div v-else-if="pageIndex == 1">
        <div class="titlebox">表单基本信息</div>
        <div class="bodyBox">
          <editStep2 ref="step2" :formInfo="formInfo" @setData="step2setData"></editStep2>
        </div>
      </div>

      <!-- 步骤三 -->
      <div v-else-if="pageIndex == 2">
        <div class="titlebox">选择数据表</div>
        <div class="bodyBox">
          <editStep3
            ref="step3"
            :datasourceid="formInfo.step2.datasource"
            :tableData="formInfo.step3.data"
            @setData="step3setData"
          ></editStep3>
        </div>
      </div>

      <!-- 步骤四 -->
      <div v-else-if="pageIndex == 3">
        <!-- <div class="titlebox">设计表单</div> -->
        <editStep4
          ref="step4"
          :formInfo="formInfo"
          :stepList="stepList"
          @setData="step4setData"
          @f_getLayout="s_getLayout"
        ></editStep4>
      </div>
    </a-card>
    <div class="buttonBox">
      <a-button :style="{ marginRight: '8px' }" @click="back" icon="rollback"> 返回引导页 </a-button>
      <a-button
        v-if="pageIndex != 3"
        :loading="loading"
        :style="{ marginRight: '8px' }"
        type="primary"
        icon="check"
        @click="next"
      >
        下一步
      </a-button>
      <template v-else>
        <a-button :style="{ marginRight: '8px' }" type="primary" @click="handelSaveDraft" icon="file-word">
          存草稿
        </a-button>

        <a-button :style="{ marginRight: '8px' }" type="primary" icon="check" @click="handelSaveAll"> 完成 </a-button>
      </template>
    </div>
    <a-modal title="选择申请主体" :visible="showMainFields" @ok="handleOk" @cancel="handleCancel">
      <a-form-model :label-col="{ span: 4 }" :wrapper-col="{ span: 20 }">
        <a-form-model-item label="申请主体" required>
          <a-select v-model="mainTableField">
            <a-select-option v-for="mainField in mainFields" :key="mainField.pk" :value="mainField.pk">
              {{ mainField.pk }}({{ mainField.pkname }})
            </a-select-option>
          </a-select>
        </a-form-model-item>
      </a-form-model>
    </a-modal>
    <!-- 选择主字段 -->
  </page-header-wrapper>
</template>

<script>
import {
  findOptionalProcessList,
  flowImage,
  viewAct_dsn_form_define,
  saveAct_dsn_form_define
} from '@/api/workflow/act_dsn_form_define.js'
import { queryListByFormId, batchSave } from '@/api/workflow/act_dsn_form_table.js'
import { viewLayoutByStepId, listByFormid, saveDraftOrAll } from '@/api/workflow/act_dsn_form_layout.js'
import { findTableFieldListByDataSourceId } from '@/api/base/table_meta.js'
import editStep2 from '@/views/workflow/Wf_FormEditStep2.vue'
import editStep3 from '@/views/workflow/Wf_FormEditStep3.vue'
import editStep4 from '@/views/workflow/Wf_FormEditStep4.vue'
import Viewer from 'viewerjs'
import { treeList } from '@/utils/formassembly/generaltree.js'
import { findStepRelation } from '@/api/workflow/act_dsn_form_step.js'
export default {
  data() {
    return {
      stepList: [], // 流程环节列表
      formInfo: {
        formid: undefined,
        operation: null,
        step2: {
          key_: undefined, // 流程key
          name_: null, // 流程名
          description_: null, // 描述
          category_: [], // 分类
          datasource: undefined // 数据源
        },
        step3: {
          data: [] // 已设置的表数据
          //   tablename_: null, // 表名
          //   description: null, // 说明
          //   type_: null, // 类型
          //   primarykey_: null, // 主键
          //   foreignkey_: null // 外键
        },
        step4: {
          layout: {
            id: null,
            formid_: null,
            type_: null,
            layout_: null
          } // 布局实体对象
        }
      }, // 各个环节的信息
      processList: [], // 步骤一可选择的流程
      pageIndex: 0, // 页面展示的目标节点
      stepIndex: 0, // 已经完成的目标节点
      url: null, // 流程图地址
      imageLoading: false, // 图片load
      loading: false, // 按钮load
      pageLoad: false,
      editDataSource: false,
      hidden: false,
      mainFields: [], // 选择的主表字段
      showMainFields: false,
      mainTableField: ''
    }
  },
  async created() {
    this.pageLoad = true
    // console.log('路由参数---', this.$route.params)
    if (this.$route.params.formid != 'undefined') {
      this.formInfo.formid = this.$route.params.formid
    }
    if (this.$route.params.operation) {
      this.formInfo.operation = this.$route.params.operation
    }
    if (this.formInfo.formid) {
      let stepIndex = 0
      let pageIndex = 1
      const req_define = await viewAct_dsn_form_define({ formid: this.formInfo.formid })
      console.log('流程表单定义', req_define)
      if (req_define.code == 0 && req_define.data) {
        Object.keys(this.formInfo.step2).forEach(key => {
          this.formInfo.step2[key] = req_define.data[key]
        })
        if (this.formInfo.step2.datasource) {
          stepIndex = 1
          pageIndex = 1
        }
        this.formInfo.step2.category_ = [this.formInfo.step2.category_]
      }
      // 判断跳转到步骤三
      const req_table = await queryListByFormId({ formid: this.formInfo.formid })
      // console.log('queryListByFormId', req_table)
      if (req_table.code == 0 && req_table.data && req_table.data.length) {
        this.formInfo.step3.data = req_table.data
        const tableName = req_table.data.map(item => item.tabname_)
        // console.log('选择的表', tableName)
        const req_field = await findTableFieldListByDataSourceId(this.formInfo.step2.datasource, tableName)
        // console.log('findTableFieldListByDataSourceId', req_field)
        if (req_field.code == 0 && req_field.data) {
          this.formInfo.step3.data.forEach(item => {
            const target = req_field.data.find(field => item.tabname_ == field.name)
            // console.log('target', target)
            if (target) {
              item.fields = target.data
            }
          })
          //   console.log('编辑时的data', this.formInfo.step3.data)
        }
        stepIndex = 2
        pageIndex = 2
      }
      // 判断跳转到步骤四
      const { data } = await listByFormid({ formid: this.formInfo.formid })
      if (data) {
        // 查询流程环节列表
        const resStep = await findStepRelation(this.formInfo.formid, 2)
        this.stepList = resStep.data
        // 根据环节id查询表单布局
        const resLayout = await viewLayoutByStepId({formid: this.formInfo.formid, stepid: this.stepList[0].id})
        await this.s_getLayout(this.stepList[0].id)
        this.formInfo.step4.layout = resLayout.data
        this.stepIndex = stepIndex = 3
        this.pageIndex = pageIndex = 3
      }
    } else {
      this.findOptionalProcessList()
    }
    this.pageLoad = false
  },
  methods: {
    // 查询表单布局
    async s_getLayout(stepid) {
      const resLayout = await viewLayoutByStepId({ formid: this.formInfo.formid, stepid: stepid })
      // console.log('重新赋值', resLayout)
      this.formInfo.step4.layout = resLayout.data
    },
    processChange(e) {
      this.url = null
      if (e) {
        this.processList.forEach(item => {
          if (item.model_key == e) {
            this.formInfo.step2.name_ = item.name
          }
        })
      }
      //   console.log(e, this.formInfo.step2.name_)
    },
    // 子组件给值
    step2setData(data) {
      //   this.formInfo['step' + index] = data
      //   console.log('.....',this.formInfo.step2.datasource , data.datasource , this.formInfo.step2.datasource != data.datasource)
      if (this.formInfo.step2.datasource && data.datasource && this.formInfo.step2.datasource != data.datasource) {
        this.editDataSource = true
      }
      Object.keys(data).forEach(key => {
        this.formInfo.step2[key] = data[key]
      })
      // console.log('给的值', this.formInfo['step' + index], index, data)
    },
    step3setData(data) {
      this.formInfo.step3.data = data
      // console.log('给的值', this.formInfo['step' + index], index, data)
    },
    step4setData(data) {
      this.formInfo.step4.layout = data
      // console.log('给的值', this.formInfo['step' + index], index, data)
    },
    // 查询可选流程列表
    findOptionalProcessList() {
      findOptionalProcessList({ tenantId: '' }).then(res => {
        // console.log('可选流程', res)
        if (res.code == 0) {
          this.processList = res.data
        }
      })
    },
    stepChange(current) {
      if (this.pageIndex == current) {
        return
      }
      if (this.stepIndex >= current) {
        this.pageIndex = current
      }
      //   console.log('current', current, 'this.stepIndex', this.stepIndex, 'this.pageIndex', this.pageIndex)
    },
    // 去环节配置
    nodeGuide() {
      this.$router.push({ path: `/Wf_NodeGuide/${this.formInfo.operation}/${this.formInfo.formid}` })
    },
    back() {
      this.$confirm({
        title: '提示',
        content: `当前界面的改动不会保存，确认返回引导页吗？`,
        okText: '是',
        okType: 'danger',
        cancelText: '否',
        onOk: () => {
          // console.log('OK')
          this.$router.push({ path: `/Wf_FormGuide/${this.formInfo.operation}/${this.formInfo.formid}` })
        },
        onCancel: () => {
          // console.log('Cancel')
          // this.$router.push({ path: `/Wf_FormGuide/${this.formInfo.operation}/${this.formInfo.formid}` })
        }
      })
    },
    async next() {
      this.loading = true
      if (this.pageIndex == 0) {
        // 流程选择，数据不持久化
        if (!this.formInfo.step2.key_) {
          this.$refs.proSelect.focus()
          this.$message.warning('请选择流程')
          this.loading = false
          return
        }
        this.pageIndexAdd()
      } else if (this.pageIndex == 1) {
        // 数据源保存，流程定义数据持久化
        if (this.$refs.step2.validate()) {
          this.$refs.step2.setData()
          const defend = JSON.parse(JSON.stringify(this.formInfo.step2))
          defend.category_ = defend.category_[0]
          defend.id = this.formInfo.formid
          const res = await saveAct_dsn_form_define(defend, { editDataSource: this.editDataSource })
          // 修改数据源，清除后续步骤与数据源有关的数据且布局
          if (this.editDataSource && this.formInfo.step4.layout.layout_) {
            let layout_ = JSON.parse(this.formInfo.step4.layout.layout_)
            if (layout_.list.length) {
              layout_.list.forEach(item => {
                if (item.pk) {
                  item.pk = ''
                  item.pkname = ''
                }
              })
            }
            layout_ = JSON.stringify(layout_)
            // console.log('layout_', layout_)
            let layout = JSON.parse(JSON.stringify(this.formInfo.step4.layout))
            layout.layout_ = layout_
            layout.stepid_ = this.$route.params.stepid_
            const req_layout = await saveDraftOrAll(layout, { isDraft: true })
            // console.log('saveDraftOrAll', req_layout)
            if (req_layout.code == 0 && req_layout.data) {
              this.formInfo.step4.layout = req_layout.data
            }
            this.formInfo.step3.data = []
          }
          // console.log('saveAct_dsn_form_define', res)
          if (res.code == 0 && res.data) {
            this.formInfo.formid = res.data
            this.pageIndexAdd()
          }
          this.loading = false
        }
      } else if (this.pageIndex == 2) {
        let that = this
        this.$confirm({
          title: '警告提示',
          content: '此操作将会清除环节配置，如果不是您配置的表单切勿操作，是否继续？',
          okText: '是',
          cancelText: '否',
          onOk: async () => {
            console.log('第三步骤')
            // 选择流程使用到的表
            let layout_ = null
            // 如果是编辑，并且布局已经存在的话，存在表修改，则将删除的表在布局中绑定的字段也删除
            // if (that.formInfo.step3.data.length && that.formInfo.step4.layout.layout_) {
            //   const oldTableName = that.formInfo.step3.data.map(item => item.tabname_)
            //   const newTableName = that.$refs.step3.data.map(item => item.tabname_)
            //   const tableName = oldTableName.filter(item => !newTableName.includes(item))
            //   //   console.log('旧表减去新表后的tableName', tableName)
            //   if (tableName.length) {
            //     layout_ = JSON.parse(that.formInfo.step4.layout.layout_)
            //     if (layout_.list.length) {
            //       layout_.list.forEach(item => {
            //         if (item.pk && tableName.includes(item.pk.split('#')[0])) {
            //           item.pk = ''
            //           item.pkname = ''
            //         }
            //       })
            //     }
            //     // console.log('修改表后的layout_', layout_)
            //     layout_ = JSON.stringify(layout_)
            //   }
            // }
            if (that.$refs.step3.validate()) {
              that.$refs.step3.setData()
              const data = JSON.parse(JSON.stringify(that.formInfo.step3.data)).map(item => {
                // console.log('that.formInfo.formid', that.formInfo.formid)
                item.formid_ = that.formInfo.formid
                delete item.fields
                return item
              })
              //   console.log('待保存的表数据', data)

              const res = await batchSave(data, {
                id: that.formInfo?.step4?.layout?.id,
                layout_: layout_
              })
              if (res.code == 0) {
                that.pageIndexAdd()
                if (layout_) {
                  that.formInfo.step4.layout.layout_ = layout_
                }
              }
              that.loading = false
            }
          },
          onCancel: () => {}
        })
      } else if (this.pageIndex == 3) {
        // 布局
        if (this.$refs.step4.validate()) {
          this.$refs.step4.setData()
        }
      }
      this.loading = false
    },
    pageIndexAdd() {
      if (this.pageIndex == this.stepIndex) {
        this.stepIndex++
      }
      this.pageIndex++
    },
    getFieldData(data, name) {
      const fields = []
      const traverse = array => {
        array.forEach(element => {
          if (element.type === 'grid' || element.type === 'tabs') {
            // 栅格布局
            element.columns.forEach(item => {
              traverse(item.list)
            })
          } else if (element.type === 'card') {
            // 卡片布局
            traverse(element.list)
          } else if (element.type === 'batch') {
            // 动态表格内复制
            traverse(element.list)
          } else if (element.type === 'table') {
            // 表格布局
            element.trs.forEach(item => {
              item.tds.forEach(val => {
                traverse(val.list)
              })
            })
          } else {
            if (element.model && element.pk && element.pk.indexOf(name) >= 0) {
              fields.push({ pk: element.pk, pkname: element.pkname })
            }
          }
        })
      }
      traverse(data)
      return fields
    },
    // 存草稿
    async handelSaveDraft() {
      this.loading = true
      this.$refs.step4.setData()
      let layout = JSON.parse(JSON.stringify(this.formInfo.step4.layout))
      layout.formid_ = this.formInfo.formid
      // 添加组件配置
      layout.layout_.componentJson = {}
      layout.layout_.componentJson.analysisObj = this.$store.state.com_config.analysisObj
      layout.layout_.componentJson.originalObj = this.$store.state.com_config.originalObj

      // delete layout.layout_.componentJson.analysisObj.factoryConfig['factory_table']
      // console.log('组件配置', layout.layout_.componentConfig)

      // 添加回显配置
      if (JSON.stringify(this.$store.state.formJson.handleObj) != '{}') {
        layout.layout_.formJson = {}
        layout.layout_.formJson.formObj = this.$store.state.formJson.formObj
        layout.layout_.formJson.handleObj = this.$store.state.formJson.handleObj
      }
      // 添加树配置
      // delete layout.layout_['treeList']
      console.log('treeList', treeList)
      layout.layout_.treeList = treeList
      //       delete layout.layout_.formJson.handleObj.PREACCE
      //       delete layout.layout_.formJson.formObj.DROP.PREACCE
      console.log('保存回显配置', layout.layout_)

      layout.layout_ = JSON.stringify(layout.layout_)
      layout.stepid_ = this.$route.params.stepid_
      console.log('草稿layout', layout)
      const req_layout = await saveDraftOrAll(layout, { isDraft: true })
      //   console.log('saveDraftOrAll', req_layout)
      if (req_layout.code == 0 && req_layout.data) {
        this.formInfo.step4.layout = req_layout.data
        this.$message.success('草稿保存成功')
      } else {
        this.$message.warning('草稿保存失败')
      }
      this.loading = false
    },
    // 完成
    async handelSaveAll() {
      this.loading = true
      let mainTable = null
      if (this.formInfo.step3.data.length) {
        mainTable = this.formInfo.step3.data.find(table => table.type_ == 90400)
        if (!mainTable) {
          this.loading = false
          this.$message.error('主表未设置')
          return
        }
      }
      //   console.log('mainTable', mainTable)
      if (!this.$refs.step4.validate()) {
        this.loading = false
        return
      }

      //   console.log(
      //     'this.$refs.step4.$refs.formDesign.data',
      //     this.$refs.step4.$refs.formDesign.data.list,
      //     'mainTable.tabname_',
      //     mainTable.tabname_
      //   )
      if (this.$refs.step4.$refs.formDesign.data.list.length) {
        this.mainFields = this.getFieldData(this.$refs.step4.$refs.formDesign.data.list, mainTable.tabname_)
      }
      if (!this.mainFields.length) {
        this.$message.warning('请至少绑定主表的一个字段')
        return
      }
      if (this.$refs.step4.$refs.formDesign.data.config.mainField) {
        const mainField = this.$refs.step4.$refs.formDesign.data.config.mainField
        const target = this.mainFields.find(filed => filed.pk == mainField)
        if (target) {
          this.mainTableField = mainField
        } else {
          this.mainTableField = null
        }
      }
      this.showMainFields = true
    },
    async saveAll() {
      this.loading = true
      this.$refs.step4.setData()
      let layout = JSON.parse(JSON.stringify(this.formInfo.step4.layout))
      layout.formid_ = this.formInfo.formid
      layout.layout_.config.mainField = this.mainTableField
      // 添加组件配置
      layout.layout_.componentJson = {}
      layout.layout_.componentJson.analysisObj = this.$store.state.com_config.analysisObj
      layout.layout_.componentJson.originalObj = this.$store.state.com_config.originalObj
      // console.log('组件配置', layout.layout_.componentConfig)
      // 添加回显配置

      if (JSON.stringify(this.$store.state.formJson.handleObj) != '{}') {
        layout.layout_.formJson = {}
        layout.layout_.formJson.formObj = this.$store.state.formJson.formObj
        layout.layout_.formJson.handleObj = this.$store.state.formJson.handleObj
      }
      layout.layout_ = JSON.stringify(layout.layout_)
      // console.log('完成layout', layout)
      layout.stepid_ = this.$route.params.stepid_
      const req_layout = await saveDraftOrAll(layout, { isDraft: false })
      //   console.log('saveDraftOrAll', req_layout)
      if (req_layout.code == 0 && req_layout.data) {
        this.formInfo.step4.layout = req_layout.data
      }
      this.$confirm({
        title: '操作成功',
        content: `已完成界面布局，是否进行环节配置？`,
        okText: '是',
        okType: 'danger',
        cancelText: '否',
        onOk: () => {
          this.$router.push({ path: `/Wf_NodeGuide/${this.formInfo.operation}/${this.formInfo.formid}` })
        },
        onCancel: () => {
          this.$router.push({ path: `/Wf_FormGuide/${this.formInfo.operation}/${this.formInfo.formid}` })
        }
      })
      this.loading = false
    },
    handleOk(e) {
      if (!this.mainTableField) {
        this.$message.warning('请在主表选择一个属性作为申请主体，例如：企业名称、单位名称、申请人姓名等')
        return
      }
      this.showMainFields = false
      this.saveAll()
    },
    handleCancel(e) {
      this.showMainFields = false
      this.loading = false
    },
    golist() {
      this.$router.push({ path: '/Wf_FormList' })
    },
    // 得到预览流程图
    getFlowImage() {
      if (!this.formInfo.step2.key_) {
        return false
      }
      this.imageLoading = true
      flowImage({ modelKey: this.formInfo.step2.key_ })
        .then(response => {
          var blob = new Blob([response])
          this.url = window.URL.createObjectURL(blob) // 创建下载的链接
          this.imageLoading = false
        })
        .catch(function(e) {
          this.imageLoading = false
          //   console.log(e)
        })
    },
    // 图片添加点击事件
    initImageTools() {
      const viewer = new Viewer(this.$refs.imgTooles, {
        url: 'data-original',
        show: function() {
          viewer.update()
        },
        hide: function() {
          // 在图片消失的时候销毁viewer
          viewer.destroy()
        }
      })
    }
  },
  components: {
    editStep2,
    editStep3,
    editStep4
  }
}
</script>

<style lang="less" scoped>
.cardArea {
  background-color: #ffffff;
  padding: 28px;
}

.cardArea_title {
  display: flex;
  flex-direction: row;
  align-items: center;
  flex-wrap: wrap;
  width: 100%;
}

.cardArea_title_label {
  width: 3px;
  height: 17px;
  background-color: #5b79fb;
}

.cardArea_title_content {
  margin-left: 0.5%;
  font-size: 19px;
  font-family: Source Han Sans CN;
  font-weight: 550;
  color: #232323;
  letter-spacing: 2px;
}

.cardArea_step {
  margin-top: 40px;
}

.stepBox {
  margin: 20px 0;
  width: 80%;
}
.buttonBox {
  text-align: center;
  margin-top: 10px;
}
.bodyBox {
  margin-top: 20px;
}
.titlebox {
  font-size: 20px;
  line-height: 20px;
  font-weight: 800;
  text-align: center;
}

.emptyrow {
  margin-top: 3em;
}
</style>
